import axios from "axios";
import { BASE_URL } from "./tools";
import { getToken } from "./auth";
import { Notify } from "vant";

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 5000,
});

// 请求拦截 (可以把统一的请求头儿放里面)
instance.interceptors.request.use(
  function(config) {
    if (getToken) {
      //统一设置请求头
      config.headers.authorization = "Bearer " + getToken();
    }
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

// 响应拦截
instance.interceptors.response.use(
  function(response) {
    return response.data;
  },
  function(error) {
    const { status } = error.response;
    if (status === 401) {
      Notify({ type: "warning", message: "未授权请先登录" });
      window.location.href = "#/login";
    }
    return Promise.reject(error);
  }
);

// 封装get请求
export const get = (url, params) => instance.get(url, { params: params });
// 封装post请求
export const post = (url, data) => instance.post(url, data);
// 封装delete请求
export const del = (url, params) => instance.delete(url, { params });

export default instance;
